package com.iflytek.ci.common.service.impl;

import com.google.common.collect.Maps;
import com.iflytek.ci.common.service.MilestoneMailService;
import com.iflytek.ci.cpms.domain.Milestone;
import com.iflytek.ci.cpms.dto.MilestoneReport;
import com.iflytek.ci.cpms.dto.ProjectInformation;
import com.iflytek.ci.cpms.service.ProjectService;
import com.iflytek.ci.cums.domain.Account;
import com.iflytek.ci.main.dto.Prior;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service("MilestoneMail")
public class MilestoneMailServiceImpl implements MilestoneMailService {

	/** 日志 */
	private static Logger logger = LoggerFactory.getLogger(MilestoneMailService.class);
	/** 注入项目Freemarker 模板 */
	private Template new_template;
    /** 里程碑报告Freemarker 模板 */
    private Template milestone_report_template;
	/** 邮件发送 */
	@Autowired
	private MimeMailService mimeMailService;
	/** Spring 异步执行 */
	@Qualifier("asynTaskExecutor")
	@Autowired
	private TaskExecutor taskExecutor;
	@Autowired
	private ProjectService projectService;
	@Value("${data_issue_path}")
	String issue_path;

	@Override
	public void new_milestone(final ProjectInformation projectinfo,
			final Milestone milestone_new, final String from) {
		taskExecutor.execute(new Runnable() {
			@Override
			public void run() {
				try {
					for (Account account : projectinfo.getAccounts()) {
						final Map<String, Object> context = Maps
								.newConcurrentMap();
						context.put("milestone", milestone_new);
						context.put("project", projectinfo.getProject());
						context.put("account", account);
						String content = FreeMarkerTemplateUtils
								.processTemplateIntoString(new_template,
										context);
						String subject = "里程碑" + milestone_new.getName() + "";

						String to = account.getMail();
						mimeMailService.sendNotificationMailSimple(
								"gczx_support@iflytek.com", to, content,
								subject);
					}
				} catch (Exception e) {
					logger.debug("ERROR with send email!");
				}
			}
		});

	}

	/**
	 * 注入Freemarker引擎配置,构造Freemarker内容模板.
	 * 
	 * @param freemarkerConfiguration
	 *            freemarker
	 * @throws java.io.IOException
	 *             IO异常
	 */
	@Autowired
	public void setFreemarkerConfiguration(
			@Qualifier("milestoneFreemarkerConfiguration") Configuration freemarkerConfiguration)
			throws IOException {
		new_template = freemarkerConfiguration.getTemplate("new_milestone.ftl",
				Prior.DEFAULT_ENCODING);
		milestone_report_template = freemarkerConfiguration.getTemplate("milestone_report.ftl",Prior.DEFAULT_ENCODING);
	}
    @Override
    public  void send_milestone_report_mail(MilestoneReport milestoneReport){
//             List<String> emails =  new ArrayList<String>();
        String [] emails =  milestoneReport.getEmails().split(Prior.SEMICOLON);
        final Map<String,Object>map = new HashMap<String, Object>();
        map.put("milestoneReport",milestoneReport);
        map.put("buildTime",String.format("yyyy-MM-dd HH:mm:ss",new Date()));
        try {

            String milestone_report_string = FreeMarkerTemplateUtils.processTemplateIntoString(milestone_report_template, map);
            for(String email:emails){
                String to = email;
                String content = milestone_report_string;
                String subject = String.format("[%s]项目--里程碑报告", milestoneReport.getProjectName());
//               mimeMailService.sendNotificationMailSimple("gczx_support@iflytek.com",to,content,subject);
            }
        } catch (IOException e) {
            logger.error("生成里程碑报告内容失败, FreeMarker模板不存在", e);
        } catch (TemplateException e) {
            logger.error("生成里程碑报告内容失败, FreeMarker处理失败", e);
        }
    }
}
